//
//  SINAStuAcitivtyAddCustomViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/19.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINAStuAcitivtyAddCustomViewController.h"
#import "SINACircularBeadUtils.h"
#import "SINAPickDateView.h"
#import "SINAUiviewClickLiserner.h"
#import "SINACalendarUtils.h"
#import "SINACommonTimePickView.h"
#import "SINASelectLocationViewController.h"

@interface SINAStuAcitivtyAddCustomViewController ()<PickerDateViewDelegate,UITextViewDelegate,CommonTimeSelectViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *commitView;


//开始时间
@property (weak, nonatomic) IBOutlet UIView *startTimeView;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;

//结束时间
@property (weak, nonatomic) IBOutlet UIView *endTimeView;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;


//输入内容
@property (weak, nonatomic) IBOutlet UITextView *inputDesTextView;
@property (strong, nonatomic)  UITextField *inputDesTextField;
@property (weak, nonatomic) IBOutlet UIView *inputBackgroundView;
@property (strong, nonatomic)  UIScrollView *inputScrollview;
@property (weak, nonatomic) IBOutlet UIImageView *inputImageViewIcon;


@property(nonatomic,strong) NSString *selectTimeFlag;
@property (weak, nonatomic) IBOutlet UIView *timeSelectBackgroundView;

@property(nonatomic,assign) NSInteger startYear;
@property(nonatomic,assign) NSInteger startMonth;
@property(nonatomic,assign) NSInteger startDay;
@property(nonatomic,assign) NSInteger startHour;
@property(nonatomic,assign) NSInteger startMin;

@property(nonatomic,assign) NSInteger endYear;
@property(nonatomic,assign) NSInteger endMonth;
@property(nonatomic,assign) NSInteger endDay;
@property(nonatomic,assign) NSInteger endHour;
@property(nonatomic,assign) NSInteger endMin;


@property (weak, nonatomic) IBOutlet UIView *locationView;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@property (weak, nonatomic) IBOutlet UITextField *inputAdressTextField;

@end

@implementation SINAStuAcitivtyAddCustomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initViewFunction];
    
    self.startDay=0;
    self.startMonth =0;
    self.startYear =0;
    
    self.endDay=0;
    self.endMonth =0;
    self.endYear =0;
    
    self.commitView.backgroundColor = baseButtonBackGroundColor;
    __weak typeof(self) weakSelf = self;
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.startTimeView andWithBlick:^(UIView *view) {
        [weakSelf selectStartTime];
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.endTimeView andWithBlick:^(UIView *view) {
        [weakSelf selectEndTime];
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.commitView andWithBlick:^(UIView *view) {
        [weakSelf commitDataFunction];
    }];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.locationView andWithBlick:^(UIView *view) {
        DLog(@"选择地点");
        
        SINASelectLocationViewController *selectController =[[SINASelectLocationViewController alloc]initWithNibName:@"SINASelectLocationViewController" bundle:nil ];
        [weakSelf.navigationController pushViewController:selectController animated:YES];
    }];
    
    //注册通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:)name:@"updateLocation" object:nil];
    
}

- (void)tongzhi:(NSNotification *)text{
    
    DLog(@"%@",text.userInfo[@"locationName"]);
    
    DLog(@"－－－－－接收到通知------");
    
    self.locationLabel.text =text.userInfo[@"locationName"];
    
}
-(void) initViewFunction{
    
    self.inputDesTextView.delegate=self;
    [SINACircularBeadUtils makeCircularBead:20 andView:self.commitView andIsSetBackground:NO];
     [SINACircularBeadUtils makeCircularBead:4 andView:self.inputBackgroundView andIsSetBackground:NO];
     [SINACircularBeadUtils makeCircularBead:4 andView:self.timeSelectBackgroundView andIsSetBackground:NO];
    
    
    
    UIScrollView *inputScrollview=[[UIScrollView alloc]init];
    self.inputScrollview = inputScrollview;
    self.inputScrollview.frame=CGRectMake(CGRectGetMaxX(self.inputImageViewIcon.frame)+12, 0, mainW-12*3-CGRectGetMaxX(self.inputImageViewIcon.frame), 45);
    [self.inputBackgroundView addSubview:self.inputScrollview];
    
    UITextField *inputDesTextField = [[UITextField alloc]init];
    self.inputDesTextField=inputDesTextField;
    [self.inputScrollview addSubview:self.inputDesTextField];
    self.inputDesTextField.frame=CGRectMake(0, 45/2-30/2,mainW*2, 30);
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"#4F4F4F"];
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:@"添加事项" attributes:dict];
    [self.inputDesTextField setAttributedPlaceholder:attribute];
    self.inputScrollview.contentSize=CGSizeMake(mainW*2, 0);
    [self.inputDesTextField addTarget:self action:@selector(searchTextFieldChangeAction:)   forControlEvents:UIControlEventEditingChanged];
    self.inputDesTextField.delegate=self;
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.inputDesTextField) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        //so easy
        else if (self.inputDesTextField.text.length >= 50) {
            self.inputDesTextField.text = [textField.text substringToIndex:50];
            [YPXToastView showToastViewWithText:@"输入文字限制50字以内" andDuration:3 andParentView:self.view];
            return NO;
        }
    }
    return YES;
}
- (void)searchTextFieldChangeAction: (id)sender
{
    if ([self.inputDesTextField.text length] == 0 )
    {
        DLog(@"输入无");
    }else if([self.inputDesTextField.text length] >=50){
        DLog(@"输入大于50");
        [self.view endEditing:YES];
        [YPXToastView showToastViewWithText:@"输入文字限制50字以内" andDuration:3 andParentView:self.view];
        
    }else{
         DLog(@"输入正常");
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"请输入";
        textView.textColor = [UIColor grayColor];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请输入"]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length>50) {
        textView.text = [textView.text substringWithRange:NSMakeRange(0, 50)];
    }
}
//选择开始时间
-(void) selectStartTime{
    self.selectTimeFlag = @"START";
    //选择开始时间
    [self selectTime:self.startYear :self.startMonth :self.startDay :self.startHour];
}
//选择结束时间
-(void) selectEndTime{
    self.selectTimeFlag = @"END";
    //选择结束时间
    [self selectTime:self.endYear :self.endMonth :self.endDay :self.endHour];
}
//选择时间
-(void) selectTime:(NSInteger)year :(NSInteger) month :(NSInteger) day  :(NSInteger) hour{
    
    
     [self.view endEditing:YES];
    
    SINACommonTimePickView *timePickView =[[SINACommonTimePickView alloc]init];
    if ([self.selectTimeFlag isEqualToString:@"END"]) {
        timePickView.titleLabel.text=@"结束时间";
        if (self.endYear!=0) {
            [timePickView comTimePicViewDefaultSelect:timePickView andWithYear:self.endYear andWithMonth:self.endMonth andWithDay:self.endDay andWithHoure:self.endHour andWithMin:self.endMin andWithSec:0];
        }
        
    } else {
        timePickView.titleLabel.text=@"开始时间";
        if (self.startYear!=0) {
            [timePickView comTimePicViewDefaultSelect:timePickView andWithYear:self.startYear andWithMonth:self.startMonth andWithDay:self.startDay andWithHoure:self.startHour andWithMin:self.startMin andWithSec:0];
        }
    }
    
    
    timePickView.delegate=self;
    timePickView.currentTimeStyle=YEAER_MAONTH_DAY_HOURE_MIN;
    //    [timePickView comTimePicViewDefaultSelect:timePickView andWithYear:2016 andWithMonth:1 andWithDay:22 andWithHoure:23 andWithMin:23 andWithSec:23];
    [timePickView show];
}

#pragma mark - CommonTimeSelectViewDelegate method
-(void)commonTimeSelectPickView:(SINACommonTimePickView *)customPickView andWithYear:(NSString *)year andWithMonth:(NSString *)month andWithDay:(NSString *)day andWithHoure:(NSString *)hour andWithMin:(NSString *)min andWithSec:(NSString *)sec{
    DLog(@"end time select %@年%@月%@日 %@时%@分%@秒",year,month,day,hour,min,sec);
    NSString *monthString =[NSString stringWithFormat:@"%ld",[month integerValue]];
    NSString *dayString =[NSString stringWithFormat:@"%ld",[day integerValue]];
    
    NSString *hourString =[NSString stringWithFormat:@"%ld",[hour integerValue]];
    NSString *minString =[NSString stringWithFormat:@"%ld",[min integerValue]];
    if ([month integerValue]<=9) {
        monthString =[NSString stringWithFormat:@"0%@",monthString];
    } else {
        monthString =[NSString stringWithFormat:@"%@",monthString];
    }
    if ([day integerValue]<=9) {
        dayString =[NSString stringWithFormat:@"0%@",dayString];
    } else {
        dayString =[NSString stringWithFormat:@"%@",dayString];
    }
    
    if ([hour integerValue]<=9) {
        hourString =[NSString stringWithFormat:@"0%@",hourString];
    } else {
        hourString =[NSString stringWithFormat:@"%@",hourString];
    }
    
    if ([min integerValue] <=9) {
        minString =[NSString stringWithFormat:@"0%@",minString];
    } else {
        minString =[NSString stringWithFormat:@"%@",minString];
    }
    if ([self.selectTimeFlag isEqualToString:@"START"]) {
        self.startYear=[year integerValue];
        self.startMonth=[month integerValue];
        self.startDay=[day integerValue];
        
        self.startHour=[hour integerValue];
        self.startMin=[min integerValue];
        
        self.startTimeLabel.text=[NSString stringWithFormat:@"%@-%@-%@-%@:%@",year,monthString,dayString,hourString,minString];
    }else{
        self.endYear=[year integerValue];
        self.endMonth=[month integerValue];
        self.endDay=[day integerValue];
        
        self.endHour=[hour integerValue];
        self.endHour=[min integerValue];
        self.endTimeLabel.text=[NSString stringWithFormat:@"%@-%@-%@-%@:%@",year,monthString,dayString,hourString,minString];
    }
}

- (void)dismissServiceTimeSelectPickView:(SINACommonTimePickView *)customPickView
{
    
}

#pragma mark -  BasePickViewDelegate method
- (void)dismissBasePickView:(SINABasePickView *)customPickView
{
    
}

-(void)pickerDateView:(SINAPickDateView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day selectHours:(NSInteger)hour{
    
}

-(void)pickerDateView:(SINAPickDateView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day selectHours:(NSInteger)hour selectMins:(NSInteger)min selectSecond:(NSInteger)second{
    
    NSString *monthString =[NSString stringWithFormat:@"%ld",(long)month];
    NSString *dayString =[NSString stringWithFormat:@"%ld",(long)day];
    
    NSString *hourString =[NSString stringWithFormat:@"%ld",(long)hour];
    NSString *minString =[NSString stringWithFormat:@"%ld",(long)min];
    if (month<=9) {
        monthString =[NSString stringWithFormat:@"0%ld",(long)month];
    } else {
        monthString =[NSString stringWithFormat:@"%ld",(long)month];
    }
    if (day<=9) {
        dayString =[NSString stringWithFormat:@"0%ld",(long)day];
    } else {
        dayString =[NSString stringWithFormat:@"%ld",(long)day];
    }
    
    if (hour<=9) {
        hourString =[NSString stringWithFormat:@"0%ld",(long)hour];
    } else {
        hourString =[NSString stringWithFormat:@"%ld",(long)hour];
    }
    
    if (min<=9) {
        minString =[NSString stringWithFormat:@"0%ld",(long)min];
    } else {
        minString =[NSString stringWithFormat:@"%ld",(long)min];
    }
    if ([self.selectTimeFlag isEqualToString:@"START"]) {
        DLog(@" star time select %ld年%ld月%ld日 %ld时%ld分%ld秒",(long)year,(long)month,(long)day,(long)hour,(long)min,(long)second);
        
        self.startTimeLabel.text=[NSString stringWithFormat:@"%ld-%@-%@-%@:%@",(long)year,monthString,dayString,hourString,minString];
    }else{
        DLog(@"end time select %ld年%ld月%ld日 %ld时%ld分%ld秒",(long)year,(long)month,(long)day,(long)hour,(long)min,(long)second);
        self.endTimeLabel.text=[NSString stringWithFormat:@"%ld-%@-%@-%@:%@",(long)year,monthString,dayString,hourString,minString];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


//提交数据
-(void) commitDataFunction{
    
   
    NSString *content = self.inputDesTextField.text;
    if (content==nil||content.length<1||[content isEqualToString:@"请输入"]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入活动事项" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    //开始时间
    NSString *address =self.startTimeLabel.text;
    if (address==nil||address.length<1||[address isEqualToString:@"请选择"]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请选择开始时间" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    //结束时间
    NSString *endTime =self.endTimeLabel.text;
    if (endTime==nil||endTime.length<1||[endTime isEqualToString:@"请选择"]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请选择结束时间" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    //地点
    NSString *location =self.locationLabel.text;
//    NSString *location =self.inputAdressTextField.text;
    if (location==nil||location.length<1||[location isEqualToString:@"请选择"]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入活动地点" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
   
    //开始时间 时分秒格式 String starttime
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd-HH:mm";
    
    
    
    NSString * dateString1 = self.startTimeLabel.text;
    NSDate * date = [df dateFromString:dateString1];
    NSString * askStartTime=[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date]];
    [dict setObject:askStartTime forKey:@"starttime"];
    //结束时间 时分秒格式 String endtime
    
    NSString * dateString2 = self.endTimeLabel.text;
    NSDate * date2 = [df dateFromString:dateString2];
    NSString * askEndTime=[NSString stringWithFormat:@"%llu",[SINACalendarUtils getDateTimeTOMilliSeconds:date2]];
    [dict setObject:askEndTime forKey:@"endtime"];
    
    if ([askStartTime integerValue]<=[[SINACalendarUtils currentTimeStr]integerValue]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"开始时间必须大于当前时间" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    //时间校验
    if ([askEndTime integerValue]<=[askStartTime integerValue]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"结束时间必须大于开始时间" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    if ((self.startYear!=self.endYear)||(self.startMonth!=self.endMonth)||(self.startDay!=self.endDay)) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"开始时间与结束时间必须在同一天" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    [self startLoading];
    //组队地址 String address
    [dict setObject:location forKey:@"address"];
    //自定义添加事项 String content
    [dict setObject:content forKey:@"content"];
    //创建组队的用户uuid String organizeuuid
    [dict setObject:[[SINACommonUserHelper share] getUserModel].userUid forKey:@"organizeuuid"];
    
    //类型id String type  自定义 0
    [dict setObject:[NSString stringWithFormat:@"%@",@"0"] forKey:@"type"];
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userStuHomeAddActivityUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"提交成功" sureBtn:@"去查看"
                                                                 cancleBtn:nil];
            alertView.resultIndex = ^(NSInteger index) {
                
                //创建通知
                NSNotification *notification =[NSNotification notificationWithName:@"stuActivityAddFindOther" object:nil userInfo:dict];
                // 通过 通知中心 发送 通知
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
                
            };
            [alertView showXLAlertView];
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"网络异常" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}

@end
